package com.ray.service;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.ray.bean.CompanyMaterialCountBean;
import com.ray.bean.DatatablesViewPageBean;
import com.ray.bean.FeedOrderDetailBean;
import com.ray.bean.FeedUseMaterialCountBean;
import com.ray.bean.OrderInfoDetailBean;
import com.ray.exception.ServiceException;
import com.ray.mapper.CompanyMaterialCountMapper;
import com.ray.mapper.ProductionUnitFeedMapper;
import com.ray.mapper.ReturnWarehouseToProviderMapper;
import com.ray.pojo.MyUser;
import com.ray.pojo.ProductionUnitOrderPojo;
import com.ray.pojo.ReturnOrderDetailPojo;
import com.ray.util.MathUtil;
import com.ray.util.RequestUtil;

import net.sf.json.JSONArray;

@Service
public class ProductionUnitFeedService {
	
	@Autowired
	ProductionUnitFeedMapper productionUnitFeedMapper;
	@Autowired
	CompanyMaterialCountMapper companyMaterialCountMapper;
	@Autowired
	ReturnWarehouseToProviderMapper returnWarehouseToProviderMapper;
	
	@Autowired
	OrderService orderService;
	@Autowired
	DuplicateOrderUpdateRecordsService duplicateOrderUpdateRecordsService;
	@Autowired
	PurchaseOrderService purchaseOrderService;

	public BigDecimal getProductionUnitCount(Map<String, Object> map) {
		//原料仓物料库存
		CompanyMaterialCountBean companyMaterialCountBean = companyMaterialCountMapper.getCompanyMaterialCountByMaterial(map);
		//投料单占用表物料已占用数
		FeedUseMaterialCountBean feedUseMaterialCountBean = productionUnitFeedMapper.getFeedUseMaterialProductionUnitCount(map);
		//判断物料
		if(companyMaterialCountBean==null) {
			return new BigDecimal("0.0");
		}
		//原材料仓生产单位库存数
		BigDecimal materialProductionUnitCount = new BigDecimal(companyMaterialCountBean.getProductionUnitCount().toString());
		//投料单生产单位占用数 
		BigDecimal feedUseProductionUnitCount = new BigDecimal("0.0");
		if(feedUseMaterialCountBean!=null && feedUseMaterialCountBean.getProductionUnitUseCount()!=null) {
			 feedUseProductionUnitCount = new BigDecimal(feedUseMaterialCountBean.getProductionUnitUseCount().toString());
		}
		//退货给供应商的生产单位数量
		Map<String,String> paramMap = new HashMap<String,String>();
		paramMap.put("materialCode", companyMaterialCountBean.getMaterialCode());
		paramMap.put("loginCompany", companyMaterialCountBean.getCompany());
		double returnToProvderProductCount = returnWarehouseToProviderMapper.getNotApprovalToProviderCount(paramMap);
		BigDecimal bigReturnToProvderProductCount = new BigDecimal(returnToProvderProductCount+"");
		if(materialProductionUnitCount.subtract(feedUseProductionUnitCount).subtract(bigReturnToProvderProductCount).doubleValue()<=0) {
			return new BigDecimal("0.0");
		}else {
			return materialProductionUnitCount.subtract(feedUseProductionUnitCount).subtract(bigReturnToProvderProductCount);
		}
	}
	
	/**
	 * 
	* @date 2018年7月17日 上午8:40:18 
	* @author 李斌
	* @return List<OrderInfoDetailBean> 
	* @throws
	 */
	public List<OrderInfoDetailBean> getOrderIdOnOrderInfoDetailByOrderDetail(Map<String, Object> map) {
		return productionUnitFeedMapper.getOrderIdOnOrderInfoDetailByOrderDetail(map);
	}
	/**
	 * 获取未生成投料单的订单(汇总) 
	* @date 2018年7月18日 上午11:35:25 
	* @author 李斌
	* @return DatatablesViewPageBean<OrderInfoDetailBean> 
	* @throws
	 */
	public DatatablesViewPageBean<OrderInfoDetailBean> getOrderInfoDetailByNotFeed(Map<String, Object> map) {
		DatatablesViewPageBean<OrderInfoDetailBean> dtcpb = new DatatablesViewPageBean<OrderInfoDetailBean>();
		ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();  
		//增加投料单物料相同是否合并
        HttpServletRequest request = attributes.getRequest();  
        MyUser user=RequestUtil.getLoginUser(request);
        map.put("feedOrderMerge", user.getCompanyInfo().getFeedOrderMerge());
		List<OrderInfoDetailBean> orderInfoDetailList = productionUnitFeedMapper.getOrderInfoDetailByNotFeedData(map);
		int count = productionUnitFeedMapper.getOrderInfoDetailByNotFeedCount(map);
		Map<String,Object> productionMap = new HashMap<String,Object>();
		for(OrderInfoDetailBean orderInfoDetailBean:orderInfoDetailList) {
			//不等于付时,才有后续 
			if( !"付".equals(orderInfoDetailBean.getUnit())) {
				if(orderInfoDetailBean.getMaterialCode()!=null&& !orderInfoDetailBean.getMaterialCode().equals("")) {
					productionMap.put("inOutUnit", orderInfoDetailBean.getUnit());
					productionMap.put("materialName", orderInfoDetailBean.getMaterialName());
					productionMap.put("color", orderInfoDetailBean.getColor()==null?"":orderInfoDetailBean.getColor().trim());
					productionMap.put("model", orderInfoDetailBean.getMaterialModel());
					productionMap.put("providerName", orderInfoDetailBean.getProviderName());
					productionMap.put("materialCode", orderInfoDetailBean.getMaterialCode());
					productionMap.put("loginCompany", map.get("loginCompany"));
					//查询生产单位库存数 
					BigDecimal productionUnitCount = this.getProductionUnitCount(productionMap);
					orderInfoDetailBean.setProductionUnitFeedCount(productionUnitCount.doubleValue());
				}else {
					orderInfoDetailBean.setProductionUnitFeedCount(0.0);
				}
			}else { 
				orderInfoDetailBean.setProductionUnitFeedCount(0.0);
			}
			//如果物料代码不为空 代表以及补全了
			if(!"".equals(orderInfoDetailBean.getMaterialCode())) {
				//查询可用数
				double availableCount = purchaseOrderService.getMaterialAvailableCount(orderInfoDetailBean.getMaterialCode(), map.get("loginCompany").toString());
				orderInfoDetailBean.setAvailableCount(availableCount);
			}
		}
		dtcpb.setiTotalDisplayRecords(count);
		dtcpb.setiTotalRecords(count); 
		dtcpb.setReturnData(orderInfoDetailList);
		return dtcpb;
	}
	
	/**
	 * 通过物料信息与订单信息查询合并前的订单明细
	* @date 2018年7月18日 下午4:01:53 
	* @author 李斌
	* @return List<OrderInfoDetailBean> 
	* @throws 
	 */
	public List<OrderInfoDetailBean> getOrderInfoDetailByMaterial(Map<String, Object> materialMap) {
		return productionUnitFeedMapper.getOrderInfoDetailByMaterial(materialMap);
	}
	
	/**
	 * 处理批量添加投料单明细
	* @date 2018年7月18日 下午7:20:39 
	* @author 李斌
	* @return String 
	* @throws
	 */
	public String saveBatchFeedOrder(Map<String,Object> map,HttpServletRequest request) throws ServiceException, ParseException {
		Map<String,Object> materialMap = new HashMap<String,Object>();
		if(map.get("feedOrderDetailArray")==null ||map.get("feedOrderDetailArray").toString().equals("")) {
			throw new ServiceException("参数信息不全异常,无投料单明细信息");
		}
		if(map.get("feedOrderMainArray")==null || map.get("feedOrderMainArray").toString().equals("")) {
			throw new ServiceException("参数信息不全异常,无投料单主表信息");
		}
		String message = "";
		//解析json 
		JSONArray feedOrderDetailJSON = JSONArray.fromObject(map.get("feedOrderDetailArray").toString());
		@SuppressWarnings("unchecked")
		List<FeedOrderDetailBean> feedDetailToOrderList = (List<FeedOrderDetailBean>) JSONArray.toCollection(feedOrderDetailJSON,FeedOrderDetailBean.class);
		//用于传给老接口的list
		List<FeedOrderDetailBean> quesetFeedList = new ArrayList<FeedOrderDetailBean>();
		//遍历传过来的投料单明细集合
		for(FeedOrderDetailBean feedOrderDetailBean:feedDetailToOrderList) {
			materialMap.put("materialCode",feedOrderDetailBean.getMaterialCode());
			materialMap.put("materialType", feedOrderDetailBean.getMaterialType());
			materialMap.put("materialFactory",feedOrderDetailBean.getMaterialFactory());
			materialMap.put("orderId",feedOrderDetailBean.getFeedOrderId());
			materialMap.put("loginCompany",map.get("loginCompany"));
			materialMap.put("haveYltsTotal",feedOrderDetailBean.getHaveYltsTotal());
			materialMap.put("colorDescription",feedOrderDetailBean.getColorDescription());
			//增加投料单物料相同是否合并
	        MyUser user=RequestUtil.getLoginUser(request);
	        if(user.getCompanyInfo().getFeedOrderMerge()==0) {//不合并
		        materialMap.put("lineNo", feedOrderDetailBean.getLineNo());
	        }
			List<OrderInfoDetailBean> orderInfoDetailBeans = this.getOrderInfoDetailByMaterial(materialMap);
			Assert.isTrue(orderInfoDetailBeans.size()>0, "该订单已生成投料单,请勿重复操作");
			//汇总后的总投料数
			BigDecimal allFeedTotal = new BigDecimal("0.0"); 
			//总生产单位占用数
			BigDecimal allProductionUnitTotal = new BigDecimal("0.0");
			//均分后的生产单位投料数
			BigDecimal allAvgProductionUnitTotal = new BigDecimal("0.0");
			if(feedOrderDetailBean.getProductionUnitFeedCount().doubleValue()>0) {
				allProductionUnitTotal = new BigDecimal(feedOrderDetailBean.getProductionUnitFeedCount().toString());
			}
			//用户填写的投料数 
			if(feedOrderDetailBean.getFeedCount()==null) {
				feedOrderDetailBean.setFeedCount(0.0);
			} 
			BigDecimal feedCount = new BigDecimal(feedOrderDetailBean.getFeedCount().toString());
			//均分后的投料总数
			BigDecimal allAvgFeedCount = new BigDecimal("0.0");
			for(OrderInfoDetailBean orderInfoDetailBean:orderInfoDetailBeans) {
				//累计投料数
				allFeedTotal = allFeedTotal.add(new BigDecimal(orderInfoDetailBean.getFeedTotal().toString()));
			}
			
			//校验 订单里面的总投料数不能小于生产单位块料数
			if(allFeedTotal.subtract(allProductionUnitTotal).doubleValue()<0) {
				throw new ServiceException("块料占用数不能大于订单投料数");
			}
			 
			//用于传输给老方法的投料明细
			List<FeedOrderDetailBean> feedOrderDetailList = new ArrayList<FeedOrderDetailBean>();
			BigDecimal orderSize = new BigDecimal(orderInfoDetailBeans.size()+"");
			BigDecimal avgActualFeedTotalSum = new BigDecimal("0");
			for(int i=0;i<orderInfoDetailBeans.size();i++) {
				//重新计算分配feedTotal  
				FeedOrderDetailBean newFeedOrderDetail = new FeedOrderDetailBean();
				newFeedOrderDetail.setMaterialCode(feedOrderDetailBean.getMaterialCode());
				newFeedOrderDetail.setMaterialName(feedOrderDetailBean.getMaterialName());
				newFeedOrderDetail.setMaterialType(feedOrderDetailBean.getMaterialType());
				newFeedOrderDetail.setMaterialFactory(feedOrderDetailBean.getMaterialFactory());
				newFeedOrderDetail.setModal(feedOrderDetailBean.getModel());
				newFeedOrderDetail.setColor(feedOrderDetailBean.getColor());
				newFeedOrderDetail.setFeedOrderId(feedOrderDetailBean.getFeedOrderId());
				newFeedOrderDetail.setLineNo(orderInfoDetailBeans.get(i).getLineNo());
				newFeedOrderDetail.setTax(feedOrderDetailBean.getTax());
				//增加采购单价
				newFeedOrderDetail.setPurchasePrice(feedOrderDetailBean.getPurchasePrice());
				newFeedOrderDetail.setColorDescription(feedOrderDetailBean.getColorDescription());//颜色描述 根据订单
				newFeedOrderDetail.setProviderName(feedOrderDetailBean.getProviderName());
				if(feedOrderDetailBean.getAgentSource().equals(2)) {//是商城
					newFeedOrderDetail.setAgent(feedOrderDetailBean.getAgent());
					newFeedOrderDetail.setAgentSource(feedOrderDetailBean.getAgentSource());
				}
				//20190514 新增
				newFeedOrderDetail.setSingleFeedCount(feedOrderDetailBean.getSingleFeedCount());
				newFeedOrderDetail.setActualFeedCount(feedOrderDetailBean.getActualFeedCount());
				newFeedOrderDetail.setUseFactoryId(feedOrderDetailBean.getUseFactoryId());
				newFeedOrderDetail.setUseFactoryCount(feedOrderDetailBean.getUseFactoryCount());
				//20200407 增加投料单备注
				newFeedOrderDetail.setFeedOrderRemark(feedOrderDetailBean.getFeedOrderRemark());
				//20190601多条订单合并问题 修正实际用料条数和使用车间数
				//20200104 修正实际用料条数多条问题及不能均分问题
				if(orderInfoDetailBeans.size()>1) {//存在多条情况
					if(i == orderInfoDetailBeans.size()-1) {//如果它是最后一条检查除不尽问题
						//总实际投料数减去获取之前的平均实际投料数总和
						newFeedOrderDetail.setActualFeedCount(
								new BigDecimal(feedOrderDetailBean.getActualFeedCount())
									.subtract(avgActualFeedTotalSum)
									.doubleValue()
								);
					}else {
						//实际用料数重新计算
						newFeedOrderDetail.setActualFeedCount(
								MathUtil.BankersRounding(
										new BigDecimal(feedOrderDetailBean.getSingleFeedCount()).multiply(new BigDecimal(orderInfoDetailBeans.get(i).getFeedTotal())).doubleValue()
										,4).doubleValue());
						//实际用料数重新计算 2
						newFeedOrderDetail.setActualFeedCount(
								MathUtil.BankersRounding(
										new BigDecimal(feedOrderDetailBean.getActualFeedCount())
												.multiply(
														new BigDecimal(orderInfoDetailBeans.get(i).getFeedTotal())
														.divide(allFeedTotal,10,BigDecimal.ROUND_HALF_DOWN))
												.doubleValue()
										,4).doubleValue());
						//累加
						avgActualFeedTotalSum = avgActualFeedTotalSum.add(new BigDecimal(newFeedOrderDetail.getActualFeedCount().toString())).setScale(4,BigDecimal.ROUND_UP);
						
					}
				}
				//如果原先有车间则实际用料数等于使用车间数
				if(newFeedOrderDetail.getUseFactoryId()!=null&&!"".equals(newFeedOrderDetail.getUseFactoryId())) {
					newFeedOrderDetail.setUseFactoryCount(newFeedOrderDetail.getActualFeedCount());
				}
				
				//保存单位,用于再次校验一下数量够不够
				newFeedOrderDetail.setUnit(feedOrderDetailBean.getUnit());
				//保存前台传过来的生产单位投料数
				
				BigDecimal feedTotal = new BigDecimal(orderInfoDetailBeans.get(i).getFeedTotal());
				//平均投料数
				//银行舍入法 四舍六入五成双 如: 2.550  保留一位小数 2.6  2.45保留一位小数 : 2.4 
				BigDecimal avgFeedCount = MathUtil.BankersRounding(feedTotal.divide(allFeedTotal,10,BigDecimal.ROUND_HALF_DOWN).multiply(feedCount).doubleValue(), 4);
				//赋值平均投料数
				newFeedOrderDetail.setFeedCount(avgFeedCount.doubleValue());
				//累加平均投料数
				allAvgFeedCount = allAvgFeedCount.add(avgFeedCount);
				//平均生产单位投料数
				BigDecimal avgProductionUnit = allProductionUnitTotal.divide(orderSize,10,BigDecimal.ROUND_HALF_DOWN);
				newFeedOrderDetail.setProductionUnitFeedCount(avgProductionUnit.doubleValue());
				allAvgProductionUnitTotal = allAvgProductionUnitTotal.add(avgProductionUnit);
				//放入集合中
				feedOrderDetailList.add(newFeedOrderDetail);
			}
			//如果用户填写的大于均分后的,所有还有剩余
			if(feedCount.subtract(allAvgFeedCount).doubleValue()>0) {
				//集合中,第一个投料单明细,让他占点便宜
				BigDecimal fristFeedCount = new BigDecimal(feedOrderDetailList.get(0).getFeedCount().toString());
				//多出来的部分
				BigDecimal surplusFeedCount = feedCount.subtract(allAvgFeedCount);
				//重新设置投料数
				feedOrderDetailList.get(0).setFeedCount(fristFeedCount.add(surplusFeedCount).doubleValue());
			}else if(feedCount.subtract(allAvgFeedCount).doubleValue()<0) {
				//集合中,第一个投料单明细,让他吃点亏
				BigDecimal fristFeedCount = new BigDecimal(feedOrderDetailList.get(0).getFeedCount().toString());
				//缺少的部分
				BigDecimal surplusFeedCount = allAvgFeedCount.subtract(feedCount);
				//重新设置投料数
				feedOrderDetailList.get(0).setFeedCount(fristFeedCount.subtract(surplusFeedCount).doubleValue());
			}
			if(allProductionUnitTotal.subtract(allAvgProductionUnitTotal).doubleValue()>0) {
				//集合中,第一个投料单明细,让他占点便宜
				BigDecimal fristProductionUnitCount = new BigDecimal(feedOrderDetailList.get(0).getProductionUnitFeedCount().toString());
				//多出来的部分
				BigDecimal surplusProductionUnitCount = allProductionUnitTotal.subtract(allAvgProductionUnitTotal);
				//重新设置投料数
				feedOrderDetailList.get(0).setFeedCount(fristProductionUnitCount.add(surplusProductionUnitCount).doubleValue());
			}else if(allProductionUnitTotal.subtract(allAvgProductionUnitTotal).doubleValue()<0) {
				//集合中,第一个投料单明细,让他吃点亏
				BigDecimal fristProductionUnitCount = new BigDecimal(feedOrderDetailList.get(0).getProductionUnitFeedCount().toString());
				//缺少的部分
				BigDecimal surplusProductionUnitCount = allAvgFeedCount.subtract(allProductionUnitTotal);
				//重新设置投料数
				feedOrderDetailList.get(0).setFeedCount(fristProductionUnitCount.subtract(surplusProductionUnitCount).doubleValue());
			}
			 
			quesetFeedList.addAll(feedOrderDetailList);
		}
		if(quesetFeedList.size()<1) {
			throw new ServiceException("无需要保存的投料单信息");
		}
		JSONArray feedDetailList = JSONArray.fromObject(quesetFeedList);
		map.put("feedOrderDetailArray", feedDetailList.toString());
		//调用老接口
		message = orderService.saveBatchFeedOrderDetailAndMain(map, request);
		if(!message.trim().equals("")) {
			message = "有部分人员微信未绑定公众号,请人工通知审核人员";
		}
		return message;
	}
	
	/**
	 * 获取原订单物料的开料尺寸与现订单的开料尺寸信息
	* @date 2018年7月23日 上午10:43:04 
	* @author 李斌
	* @return Object 
	* @throws
	 */
	public ProductionUnitOrderPojo getProductionUnitOrderPojo(Map<String, Object> map) {
		//生产单位可用总数
		BigDecimal productionUnitFeedCount = this.getProductionUnitCount(map);
		ProductionUnitOrderPojo productionUnitOrderPojo = new ProductionUnitOrderPojo();
		//设置生产单位总可用数 
		productionUnitOrderPojo.setProductionUnitFeedCount(productionUnitFeedCount.doubleValue());
		//获取退回到仓库的订单信息
		List<ReturnOrderDetailPojo> returnOrderDetailList = productionUnitFeedMapper.getReturnOrderDetail(map);
		for(ReturnOrderDetailPojo returnOrderDetailPojo:returnOrderDetailList) {
			if(returnOrderDetailPojo.getKlccSize()!=null) {
				returnOrderDetailPojo.setKlccSize(returnOrderDetailPojo.getKlccSize().trim());
			}
		} 
		//设置退回到仓库的订单信息
		productionUnitOrderPojo.setReturnOrderDetailList(returnOrderDetailList);
		//获取当前订单的订单信息
		ReturnOrderDetailPojo orderDetail = productionUnitFeedMapper.getNowOrderDetail(map);
		if(orderDetail!=null && orderDetail.getKlccSize()!=null) {
			orderDetail.setKlccSize(orderDetail.getKlccSize().trim());
		}
		productionUnitOrderPojo.setOrderDetail(orderDetail);
		return productionUnitOrderPojo;
	}
}
